package com.tubeonfire.controller.admin;

import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tubeonfire.entity.Playlist;
import com.tubeonfire.model.admin.PlaylistModel;
import com.tubeonfire.util.PlaylistValidate;

@SuppressWarnings("serial")
public class EditPlaylistServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(EditPlaylistServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try {
			HttpSession session = req.getSession();
			String id = req.getParameter("id");
			Playlist pl = PlaylistModel.byId(id, false);
			if (pl != null) {
				session.setAttribute("action", "edit");
				session.setAttribute("pl", pl);
				req.getRequestDispatcher("/admin/form_playlist.jsp").forward(
						req, resp);
			} else {
				session.setAttribute("error",
						"Playlist's not exists or has been deleted !");
				resp.sendRedirect("/admin/playlist/list");
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004,
					"We are sorry for the inconvenience ! Please try again later !");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			HttpSession session = req.getSession();
			String id = req.getParameter("id");
			Playlist pl = PlaylistModel.byId(id, false);
			if (pl != null) {
				if (PlaylistValidate
						.checkForm(req, resp, session, "edit", pl)) {
					pl.setUpdated(Calendar.getInstance().getTime());
					PlaylistModel.insert(pl);
					session.setAttribute("action", "add");
					session.setAttribute("success", "Action success !");
					resp.sendRedirect("/admin/playlist/edit?id=" + id);
				}
			} else {
				session.setAttribute("error",
						"Playlist's not exists or has been deleted !");
				resp.sendRedirect("/admin/playlist/list");
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004,
					"We are sorry for the inconvenience ! Please try again later !");
		}
	}
}
